import express from 'express';
import Ret, { RetCode, ERROR } from '../../../bean/code/Ret';
import logger, { error } from '../../../utils/logger';
const app = express();
import dayjs from 'dayjs'
import request from 'request'
import { Op } from 'Sequelize'
import { urlEncode, excludeEmpty } from '../../../utils/index';
import ConfigReader from '../../../utils/configReader';
import { db, Sequelize } from '../../../dao/config/index';
import { converPage } from '../../../bean/page';
const User = require("../../../dao/models/f_user")(db, Sequelize);
const ShippingAddress = require("../../../dao/models/f_shipping_address")(db, Sequelize);
const PersonIntegralIncome = require("../../../dao/models/f_person_integral_income")(db, Sequelize);
User.hasMany(User, {
  foreignKey: "recommenderId"
})
ShippingAddress.belongsTo(User, {
  foreignKey: "userId",
})
/**
 * 添加地址
 */
app.post("/insertAddress", async (req, res) => {
  const addressInfo = req.body;
  try {
    await ShippingAddress.upsert(addressInfo);
  } catch (e) {
    logger.error(e);
    res.json(Ret(RetCode.ERROR));
  }
  res.json(Ret(RetCode.SUCCESS));
})
/** 
 * 获取用户收货地址
 */
app.get("/getUserShippingAddress", async (req, res) => {
  const { openid } = req.query;
  const addressModel = await ShippingAddress.find({ include: { model: User, where: { openid }, attributes: [] } });
  res.json(Ret(RetCode.SUCCESS).setData(addressModel));
})
/**
 * 获取所有用户信息
 */
app.post("/getUsers", async (req, res) => {
  const params = req.body, { page = {} } = params, { pageSize = 10, pageNum = 1 } = page;
  const condition = excludeEmpty(params, User);
  const users = await User.findAndCount({ where: condition, ...converPage(pageSize, pageNum), include: [User] });
  users.count = await User.count();
  res.json(Ret(RetCode.SUCCESS).setData(users));
})

/**
 * 获取用户不同积分来源统计 
 */
app.post("/incomeDetail", async (req, res) => {
  const { userId } = req.body;
  const partten = "YYYY-MM-DD";
  // 昨日开始到结束
  const prevStartDate = dayjs(dayjs().subtract(1, 'days').format(partten)).toDate();
  const prevEndDate = dayjs(dayjs().format(partten)).toDate();
  const prevDayIncomeDetails = await PersonIntegralIncome.findAll({
    attributes: [[Sequelize.fn('SUM', Sequelize.col('integral')), 'score'], "dataofacquisition", "userid", "incomtype"], group: 'incomtype', rollup: true, where: {
      userid: userId, dataofacquisition: {
        [Op.between]: [prevStartDate, prevEndDate]
      }
    }
  });
  const totalIncomeDetails = await PersonIntegralIncome.findAll({
    attributes: [[Sequelize.fn('SUM', Sequelize.col('integral')), 'score'], "dataofacquisition", "userid", "incomtype"], group: 'incomtype', rollup: true, where: {
      userid: userId
    }
  });
  res.json({
    prevDayIncomeDetails,
    totalIncomeDetails
  });
})
export default app;
